package com.wj.service.impl;

import com.wj.pojo.CustomWorks;
import com.wj.pojo.SubmitWorks;
import com.wj.dao.SubmitWorksMapper;
import com.wj.service.ISubmitWorksService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wj.utils.RespUtil;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wj
 * @since 2022-04-15
 */
@Service
@Transactional
public class SubmitWorksServiceImpl extends ServiceImpl<SubmitWorksMapper, SubmitWorks> implements ISubmitWorksService {
    @Resource
    private SubmitWorksMapper submitWorksMapper;

    @Override
    public List<SubmitWorks> getAllSubmitWorks() {
        return submitWorksMapper.getAllSubmitWorks();
    }

    @Resource
    DataSourceTransactionManager dataSourceTransactionManager;

    @Override
    public RespUtil addSubmitWorks(Integer[] cids) {
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(definition);

        for (Integer cid : cids) {
            int i = submitWorksMapper.addSubmitWorks(cid);
            if (i<1){
                dataSourceTransactionManager.rollback(transactionStatus);
                return RespUtil.error("添加失败，有以提交过");
            }
        }
        dataSourceTransactionManager.commit(transactionStatus);
        return RespUtil.success("添加成功");
    }

    @Override
    public List<CustomWorks> searchWorks(String searchText) {
        return submitWorksMapper.searchSubmitWorks(searchText);
    }
}
